<template>
  <div class="upload-img">
    <!--
    action：提交到服务器的地址
    file-list 显示的文件列表，格式是对象数组
    list-type：文件列表类型
    on-remove：图片移除时的钩子函数
    on-preview：图片预览钩子函数
    disabled：禁用的意思
    accept="image/png, image/jpeg":约束文件类型
 -->
    <el-upload
      accept="image/png, image/jpeg"
      :class="{ disabled: value }"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :http-request="handleUpload"
    >
      <!-- +号的图标 -->
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- 图片预览弹窗 -->
    <el-dialog title="预览" :visible="isShow" @close="isShow = false">
      <img :src="value" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5"; //引入腾讯云储存对象的包
export default {
  name: "UploadImg",
  props: {
    value: {
      // 接收父传子的value属性 (头像地址)
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isShow: false,
    };
  },
  //计算属性(完整写法有get和set)
  computed: {
    fileList: {
      get() {
        //就是有头像就返回这个value，要是没头像就给空
        return this.value ? [{ url: this.value }] : [];
      },
      set() {},
    },
  },
  methods: {
    // 文件删除时的钩子函数
    handleRemove() {
      // 需要把value清空
      // 子传父，触发input事件，并传递空字符串
      this.$emit("input", "");
    },
    // 预览图片
    handlePreview() {
      this.isShow = true;
      // console.log("yulan");
    },
    //开始上传到腾讯云的储存对象
    handleUpload({ file }) {
      // console.log("开始上传");
      //把选择的图片发至腾讯云服务器
      //实例化cos
      const cos = new COS({
        SecretId: "AKIDX8c8XlofGaeT2bt68uQimcBWeYP1NTKt",
        SecretKey: "SjlY4JLWQ8ankRuJdmgMtCIApGVgicIj",
      });
      //调用方法上传
      cos.putObject(
        {
          Bucket: "heima-1317090644", //桶名
          Region: "ap-beijing", //地区
          Key: file.name, //文件名
          Body: file, //文件对象
        },
        (err, data) => {
          if (err) {
            return this.$message.success("上传失败");
          }
          // 拿到上传成功的图片地址，同步到父组件中
          this.$emit("input", `https://${data.Location}`);
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 146px;
  height: 146px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409eff;
}
.el-icon-plus {
  font-size: 60px;
  color: #8c939d;
  text-align: center;
}
.disabled {
  .el-upload {
    display: none;
  }
}
</style>
